<?php

namespace App\Http\Middleware;

use App\Http\Route;
use App\Models\Log\AccessLog;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Response;
use Illuminate\Http\Request;

class Acl
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle(Request $request, Closure $next, $guard = null)
    {
        $try = function ($desc) use ($request) {
            try {
                $accessLog = new AccessLog();
                $accessLog->user_name = Auth::user()->email;
                $accessLog->ip        = $request->ip();
                $accessLog->uri       = "/" . $request->route()->uri();
                $accessLog->time      = date("Y-m-d H:i:s");
                $accessLog->desc      = $desc;
                $accessLog->save();
            } catch (\Exception $e) {
            }
        };

        if (Auth::guard($guard)->guest()) {
            if ($request->ajax() || $request->wantsJson()) {

                $try("会话过期");
                return response('Unauthorized.', 401);
            } else {

                $try("登录成功");
                return redirect()->guest('login');
            }
        }

        if (!in_array($request->route()->uri(), ['/' , 'home'])) {
            if (Auth::user()->user_id != 1) {
            
                $allowed = false;

                $acl = \App\Models\Acl::where('role_id', Auth::user()->role_id)->where('uri', $request->route()->uri())->first();
                if ($acl) {
                    $allowed = true;
                }

                if (!$allowed) {

                    $try("禁止访问");
                    return Response::view('errors.403', [], 403);
                }
            }
        }

        $try(json_encode($p = $_REQUEST));

        view()->share('request', $request);

        $label1 = '';
        $label2 = '';

        $routes = Route::label();
        foreach ($routes as $label => $routes) {
            foreach ($routes as $name => $route) {
                if ($route['uri'] == $request->route()->uri()) {
                    $label2 = $name;
                    $label1 = $label;
                    break;
                }
            }
        }

        view()->share('label1', $label1);
        view()->share('label2', $label2);

        return $next($request);
    }
}
